package com.monkey.luffer.springboot.demo.basis.kcc;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@NoArgsConstructor
@AllArgsConstructor
@Builder
public class RsaConfig {

	public static final String ENCRYPT_ALGORITHM_RSA = "RSA";
	private String publicKey;
	private String privateKey;
	private KeyPair keyPair;
	public KeyPair getOrInitKeyPair() {
		if (keyPair == null) {
			synchronized (this) {
				if (keyPair == null) {
					initKeypair();
				}
			}
		}
		return keyPair;
	}
	@SneakyThrows
	private void initKeypair() {
		KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPT_ALGORITHM_RSA);
		byte[] pubKeyBytes = Base64.getDecoder().decode(publicKey);
		byte[] priKeyBytes = Base64.getDecoder().decode(privateKey);
		X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);
		PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(priKeyBytes);
		RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
		RSAPrivateKey privateKey = (RSAPrivateKey)keyFactory.generatePrivate(priKeySpec);
		keyPair = new KeyPair(publicKey, privateKey);
	}

	public KeyPair getKeyPair() {
		return keyPair;
	}

	public void setKeyPair(KeyPair keyPair) {
		this.keyPair = keyPair;
	}
}
